package com.jl.smartcard.ui.views.project;

import java.io.File;

import org.eclipse.core.filesystem.EFS;
import org.eclipse.core.filesystem.IFileStore;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.ViewerSorter;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.ide.FileStoreEditorInput;
import org.eclipse.ui.part.DrillDownAdapter;
import org.eclipse.ui.part.ViewPart;

import com.jl.js.console.ConsoleShell;
import com.jl.js.console.ConsoleUtil;
import com.jl.smartcard.ui.ImageShop;
import com.jl.smartcard.ui.SmartCardUI;

public class ProjectView extends ViewPart {

	/**
	 * The ID of the view as specified by the extension.
	 */
	public static final String ID = "com.jl.core.views.ProjectView";

	private TreeViewer viewer;
	private DrillDownAdapter drillDownAdapter;
	private Action refresh;
	private Action doubleClickAction;

	private Action loadJsFile;

	class NameSorter extends ViewerSorter {
	}

	/**
	 * The constructor.
	 */
	public ProjectView() {
		ProjectConfig.setTreeViewer(viewer);
	}

	/**
	 * This is a callback that will allow us to create the viewer and initialize
	 * it.
	 */
	@Override
	public void createPartControl(Composite parent) {
		viewer = new TreeViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
		drillDownAdapter = new DrillDownAdapter(viewer);
		viewer.setContentProvider(new ViewContentProvider());
		viewer.setLabelProvider(new ViewLabelProvider());
		viewer.setSorter(new NameSorter());
		viewer.setInput(NavigatorEntityFactory.setNavigatorEntity());
		viewer.expandToLevel(3);

		// Create the help context id for the viewer's control
		PlatformUI.getWorkbench().getHelpSystem()
				.setHelp(viewer.getControl(), "com.jl.core.viewer");
		makeActions();
		makeClickAction();
		hookContextMenu();
		hookDoubleClickAction();
		contributeToActionBars();
	}

	private void makeClickAction() {
		viewer.addSelectionChangedListener(new ISelectionChangedListener() {
			@Override
			public void selectionChanged(SelectionChangedEvent event) {
				ISelection selection = viewer.getSelection();
				if (selection == null) {
					return;
				}
				Object obj = ((IStructuredSelection) selection)
						.getFirstElement();
				ProjectConfig.setCurrent(obj);
			}
		});
	}

	private void hookContextMenu() {
		MenuManager menuMgr = new MenuManager("#PopupMenu");
		menuMgr.setRemoveAllWhenShown(true);
		menuMgr.addMenuListener(new IMenuListener() {
			@Override
			public void menuAboutToShow(IMenuManager manager) {
				ProjectView.this.fillContextMenu(manager);
			}
		});
		Menu menu = menuMgr.createContextMenu(viewer.getControl());
		viewer.getControl().setMenu(menu);
		getSite().registerContextMenu(menuMgr, viewer);
	}

	private void contributeToActionBars() {
		IActionBars bars = getViewSite().getActionBars();
		fillLocalPullDown(bars.getMenuManager());
		fillLocalToolBar(bars.getToolBarManager());
	}

	private void fillLocalPullDown(IMenuManager manager) {
		// manager.add(newFile);
		// manager.add(new Separator());
		// manager.add(refresh);
	}

	private void fillContextMenu(IMenuManager manager) {
		manager.add(loadJsFile);
		manager.add(new Separator());
		// manager.add(refresh);
		manager.add(new Separator());
		drillDownAdapter.addNavigationActions(manager);
		// Other plug-ins can contribute there actions here
		manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
	}

	private void fillLocalToolBar(IToolBarManager manager) {
		manager.add(refresh);
		manager.add(new Separator());
		drillDownAdapter.addNavigationActions(manager);
	}

	private void makeActions() {

		loadJsFile = new Action() {
			@Override
			public void run() {
				ISelection selection = viewer.getSelection();
				Object obj = ((IStructuredSelection) selection)
						.getFirstElement();
				if (obj instanceof TreeFile) {
					File file = ((TreeFile) (obj)).getFile();
					String cmd = ConsoleUtil.makeLoadCmd(file);
					ConsoleShell cs = ConsoleUtil.getCurrentConsoleShell();
					if (cs != null) {
						cs.inputComamndLine(cmd + '\n');
					}
				}
			}
		};

		loadJsFile.setText("Load ...");
		loadJsFile.setImageDescriptor(ImageShop.getDescriptor("run_16"));
		refresh = new Action() {
			@Override
			public void run() {
				viewer.setInput(NavigatorEntityFactory.setNavigatorEntity());
				viewer.refresh();
				viewer.expandToLevel(3);
			}
		};
		refresh.setText("refresh");
		refresh.setToolTipText("refresh navigator");
		refresh.setImageDescriptor(ImageShop.getDescriptor("refresh_16"));
		doubleClickAction = new Action() {
			@Override
			public void run() {
				ISelection selection = viewer.getSelection();
				Object obj = ((IStructuredSelection) selection)
						.getFirstElement();
				if (obj instanceof TreeFile) {
					// TODO : not implements
					TreeFile f = (TreeFile) obj;
					File file = f.getFile();
					IWorkbenchPage page = getSite().getPage();
					try {
						IFileStore fileStore = EFS
								.getStore(f.getFile().toURI());
						if (ProjectConfig.isLogFile(file)) {
							page.openEditor(
									new FileStoreEditorInput(fileStore),
									SmartCardUI.ID_EDITOR_SCR, true);
							return;
						}
						if (ProjectConfig.isJsFile(file)) {
							String ID = "org.eclipse.wst.jsdt.ui.CompilationUnitEditor";
							// page.openEditor(
							// new FileStoreEditorInput(fileStore),
							// ID, true);
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		};
	}

	private void hookDoubleClickAction() {
		viewer.addDoubleClickListener(new IDoubleClickListener() {
			@Override
			public void doubleClick(DoubleClickEvent event) {
				doubleClickAction.run();
			}
		});
	}

	/**
	 * Passing the focus request to the viewer's control.
	 */
	@Override
	public void setFocus() {
		viewer.getControl().setFocus();
	}
}